<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Models\Shortlist;
use App\Models\Shortstatistic;
use App\Models\Shortgroup;
use App\Models\Users;
use App\Models\Shortrecord;
use App\Models\Domainlist;
use App\Services\OutputService;
use App\Services\CommonService;
use App\Services\MemberService;
use App\Services\MiniappService;
use App\Services\DwzService;
use Exception,Log;

class ShortController extends Controller
{
    public function shortList(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $shortLists = Shortlist::getUserShortList($request->openid,$request->name,$request->group_id);
        // $shortIds = $shortLists->pluck("short_id")->all();
        // $yesterdays = Shortstatistic::shortYesterday($shortIds);
        // $today = date("Ymd",time());
        // $month = date("Ym01",time());
        // $shortIdString = implode('", "', $shortIds);  
        // $shortId = '("'.$shortIdString.'")';
        // $uvMonth = Shortstatistic::shortMonth($shortId,$month);
        // $uvMonths = collect($uvMonth);
        // foreach ($shortLists as $shortList) {
        //     $yesterday = $yesterdays->where("short_id",$shortList->short_id)->first();
        //     $shortList->uv_yesterday = empty($yesterday) ? 0 : $yesterday->uv;
        //     $uvMonth = $uvMonths->where("short_id",$shortList->short_id)->first();
        //     $shortList->uv_moth = empty($uvMonth) ? 0 : $uvMonth->uv;
        //     $uv_today = Redis::hget('short_uv_'.$today,$shortList->short_id);
        //     $shortList->uv_today = empty($uv_today) ? 0 : $uv_today;
        // }
        return OutputService::success("SUCCESS",["shortLists"=>$shortLists]);
    }

    public function shortAdd(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->name)) return OutputService::error("请输入链接标题!");
        if (empty($request->link)) return OutputService::error("请输入跳转链接!");
        if (mb_strlen($request->name) > 15) return OutputService::error("短链接名称不能超过15个字!");
        if (mb_strlen($request->link) > 300) return OutputService::error("长链接不能超过300个字符!");
        if ($request->end_time == "选择过期时间") {
            $end_time = 0;
        } else {
            $end_time = strtotime($request->end_time);
        }
        if (!empty($request->appid)) {
            $accessToken = MiniappService::getAccessToken($request->appid);
            if ($accessToken["status"] == "error") return OutputService::error("接口失败！");
            $checkResult = MiniappService::msgSecCheck($accessToken["access_token"],$request->name.$request->link,$request->openid);
            if (!$checkResult) return OutputService::error("输入的内容存在违规!");
        }
        $domainList = Domainlist::userDomain($request->openid);
        $domain = empty($domainList) ? "qxlwm.cn" : $domainList->domain;
        $memberParamas = MemberService::userMemberParamas($request->openid);
        $shortCount = Shortlist::getUserShortCount($request->openid);
        if ($shortCount > $memberParamas["count"]) return OutputService::error("免费用户最多创建3个短链接!");
        $name = substr($request->name, 0,15);
        $link = substr($request->link, 0,300);
        $id = Shortlist::shortLinkCreate($request->openid,$name,$link,$end_time,$request->group_id,$memberParamas["end_time"],$domain,$request->appid);
        $short_id = CommonService::decb64($id);
        if ($domain == "qxlwm.cn") {
            $dwz = "https://".$domain."/".$short_id;
        } else {
            $dwz = $domain."/".$short_id;
        }
        Shortlist::updateShortId($id,$short_id,$dwz);
        return OutputService::success("SUCCESS",["short_id"=>$short_id,"dwz"=>$dwz]);
    }

    public function shortDetial(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->short_id)) return OutputService::error("参数错误!");
        $shortList = Shortlist::shortDetial($request->openid,$request->short_id);
        if (empty($shortList)) return OutputService::error("短链接不存在!");
        $shortGroup = Shortgroup::shortGroupDetial($shortList->group_id);
        unset($shortList["id"]);
        $shortList->group_name = $shortGroup->name;
        if (empty($shortList)) return OutputService::error("短链接不存在!");
        return OutputService::success("SUCCESS",["shortList"=>$shortList]);
    }

    public function shortDetialStatic(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->short_id)) return OutputService::error("参数错误!");
        $shortList = Shortlist::shortDetial($request->openid,$request->short_id);
        if (empty($shortList)) return OutputService::error("参数错误!");
        $today = date("Ymd",time());
        $uv_today = Redis::hget('short_uv_'.$today,$request->short_id);
        $uv_today = empty($uv_today) ? 0 : $uv_today;
        $month = date("Ym01",time());
        $yesterday = date('Ymd', strtotime('-1 day'));
        $yesStatic = Shortstatistic::shortStatisticPhase($request->short_id,$yesterday);
        $uv_yesterday = empty($yesStatic) ? 0 : $yesStatic->uv;
        // 获取本月
        $monthStatic = Shortstatistic::shortDetialMonth($request->short_id,$month);
        $sumStatic = Shortstatistic::shortSumMonth($request->short_id);
        return OutputService::success("SUCCESS",["uv_today"=>$uv_today,"uv_yesterday"=>$uv_yesterday,"uv_month"=>$monthStatic+$uv_today,"uv_total"=>$sumStatic+$uv_today]);
    }

    public function shortUpdate(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->name)) return OutputService::error("请输入链接标题!");
        if (empty($request->link)) return OutputService::error("请输入跳转链接!");
        if (mb_strlen($request->name) > 15) return OutputService::error("短链接名称不能超过15个字!");
        if (mb_strlen($request->link) > 300) return OutputService::error("长链接不能超过300个字符!");
        if ($request->end_time == "选择过期时间") {
            $end_time = 0;
        } else {
            $end_time = strtotime($request->end_time);
        }
        $shortList = Shortlist::shortDetial($request->openid,$request->short_id);
        if (empty($shortList)) return OutputService::error("短链接不存在!");
        $domainList = Domainlist::userDomain($request->openid);
        $domain = empty($domainList) ? "qxlwm.cn" : $domainList->domain;
        if ($domain == "qxlwm.cn") {
            $dwz = "https://".$domain."/".$request->short_id;
        } else {
            $dwz = $domain."/".$request->short_id;
        }
        $memberParamas = MemberService::userMemberParamas($request->openid);
        Shortlist::shortLinkUpdate($request->openid,$request->short_id,$request->name,$request->link,$end_time,$request->group_id,$memberParamas["end_time"],$domain,$dwz);
        return OutputService::success("SUCCESS");
    }

    public function shortDel(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->short_id)) return OutputService::error("参数错误!");
        Shortlist::shortListDel($request->openid,$request->short_id);
        return OutputService::success("SUCCESS");
    }

    public function shortRecord(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->short_id)) return OutputService::error("参数错误!");
        $shortList = Shortlist::shortDetial($request->openid,$request->short_id);
        if (empty($shortList)) return OutputService::error("参数错误!");
        $start_time = strtotime($request->start_time);
        $end_time = strtotime($request->end_time);
        $startMonth = date("m",$start_time);
        $endMonth = date("m",$end_time);
        if ($startMonth == $endMonth) {
            // 在同一月内
            $startTbnum = ($startMonth%4);
            $kfRecordDb = new Shortrecord(["tbnum"=>$startTbnum]);
            $kfRecords = $kfRecordDb->shortRecordLists($request->short_id,$start_time,$end_time);
            return OutputService::success("SUCCESS",$kfRecords);
        } else {
            // 在不同月份
            if (empty($request->total)) {
                $startTbnum = ($startMonth%4);
                $startKfRecordDb = new Shortrecord(["tbnum"=>$startTbnum]);

                $endTbnum = ($endMonth%4);
                $endKfRecordDb = new Shortrecord(["tbnum"=>$endTbnum]);
                // 计算开始的时间
                $startCount = $startKfRecordDb->shortRecordSampleCount($request->short_id,$start_time,$end_time);
                $endCount = $endKfRecordDb->shortRecordSampleCount($request->short_id,$start_time,$end_time);
                $total = $startCount+$endCount;
            } else {
                $total = $request->total;
                $startCount = $request->total_start;
                $endCount = $request->total_end;
            }
            if ($request->offset > $endCount) {
                // 第二个库查询结束,查询第一个库
                $startTbnum = ($startMonth%4);
                $startKfRecordDb = new Shortrecord(["tbnum"=>$startTbnum]);
                $kfRecords = $startKfRecordDb->shortRecordListSample($request->short_id,$start_time,$end_time,$request->offset,$request->limit);
            } else {
                if (($request->offset+$request->limit) > $endCount) {
                    // 第二个库查询剩余不足,查询1个库
                    // 先查询第二个库
                    $endTbnum = ($endMonth%4);
                    $endKfRecordDb = new Shortrecord(["tbnum"=>$endTbnum]);
                    $endkfRecords = $endKfRecordDb->shortRecordListSample($request->short_id,$start_time,$end_time,$request->offset,$request->limit);

                    // 再查询第一个库
                    $newOffset = 0;
                    $newLimit = $request->limit - count($endkfRecords);
                    $startTbnum = ($startMonth%4);
                    $startKfRecordDb = new Shortrecord(["tbnum"=>$startTbnum]);
                    $startkfRecords = $startKfRecordDb->shortRecordListSample($request->short_id,$start_time,$end_time,$newOffset,$newLimit);
                    $kfRecords = $endkfRecords->merge($startkfRecords)->all();
                } else {
                    // 查询第二个库
                    $endTbnum = ($endMonth%4);
                    $endKfRecordDb = new Shortrecord(["tbnum"=>$endTbnum]);
                    $kfRecords = $endKfRecordDb->shortRecordListSample($request->short_id,$start_time,$end_time,$request->offset,$request->limit);
                }
            }
            return OutputService::success("SUCCESS",["data"=>$kfRecords,"total"=>$total,"total_start"=>$startCount,"total_end"=>$endCount]);
        }
    }

    public function shortStatic(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->short_id)) return OutputService::error("参数错误!");
        $shortList = Shortlist::shortDetial($request->openid,$request->short_id);
        if (empty($shortList)) return OutputService::error("参数错误!");
        $phase_start = str_replace("-", "",$request->start);
        $phase_end = str_replace("-", "",$request->end);
        $shortStatistics = Shortstatistic::shortStatistic($request->short_id,$phase_start,$phase_end);
        $dateLists = CommonService::getDateFromRange($request->start,$request->end,"Ymd");
        $statistics = [];
        foreach ($dateLists as $dateList) {
            $phase = str_replace("-", "", $dateList);
            $shortStatistic = $shortStatistics->where("phase",$phase)->first();
            if (empty($shortStatistic)) {
                $statistics[] = ["uv"=>0,"pv"=>0,"phase"=>$dateList];
            } else {
                $statistics[] = ["uv"=>$shortStatistic->uv,"pv"=>$shortStatistic->pv,"phase"=>$dateList];
            }
        }
        return OutputService::success("SUCCESS",["statistics"=>$statistics]);
    }

    public function groupList(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        $shortGroup = Shortgroup::getShortGroup($request->openid);
        return OutputService::success("SUCCESS",["shortGroup"=>$shortGroup]);
    }

    public function groupAdd(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (!empty($request->appid)) {
            $accessToken = MiniappService::getAccessToken($request->appid);
            if ($accessToken["status"] == "error") return OutputService::error("接口失败！");
            $checkResult = MiniappService::msgSecCheck($accessToken["access_token"],$request->name,$request->openid);
            if (!$checkResult) return OutputService::error("内容存在违规!");
        }
        $groupExist = Shortgroup::groupNameExist($request->openid,$request->name);
        if (!empty($groupExist)) return OutputService::error("分组已存在,请勿重复创建!");
        if (empty($request->group_id)) {
            $group_id = md5($request->openid.time().rand(1000,9999));
            Shortgroup::shortGroupAdd($request->openid,$group_id,$request->name);
            return OutputService::success("分组创建成功!",["group_id"=>$group_id]);
        } else {
            Shortgroup::shortGroupUpdate($request->openid,$request->group_id,$request->name);
            return OutputService::success("分组更新成功!");
        }
    }

    public function groupDelete(Request $request)
    {
        if (empty($request->openid)) return OutputService::error("参数错误!");
        if (empty($request->group_id)) return OutputService::error("参数错误!");
        Shortgroup::shortGroupDel($request->openid,$request->group_id);
        return OutputService::success("分组删除成功!");
    }

    public function recordStatic(Request $request)
    {
        if (empty($request->short_id)) return OutputService::error("参数错误!");
        if (empty($request->record_id)) return OutputService::error("参数错误!");
        $sign = md5($request->short_id."sk".$request->key);
        if ($sign != $request->sign) return OutputService::error("参数错误!");
        $record_id = $request->record_id;
        $short_id = $request->short_id;
        $code = empty($request->code) ? "" : $request->code;
        $short = Cache::get('short_'.$short_id);
        if (empty($short)) {
            $short = Shortlist::shortListDetial($short_id);
            if (empty($short)) return OutputService::error("短链接不存在或已删除!");
            Cache::put('short_'.$short_id,$short,3600);
        }
        $time = time();
        $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
        Redis::hincrby('short_uv_'.date("Ymd",time()),$short_id,1);
        $siteRecord = new Shortrecord(["tbnum"=>$record_id[0]]);
        $siteRecord->creatShortRecord($record_id,$short_id,$code,$request->system,$request->browser,$request->device,$ip);
        return OutputService::success("SUCCESS",["short"=>$short]);
    }
}